<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>JS基础</title>
	</head>
	<body>
		<h3>question1. 用js打印一个乘法表</h3>
		<button type="button" onclick="question1()">测试</button>
		<h3>question2.斐波那契数列函数(30以内)</h3>
		<button type="button" onclick="question2(30)">测试</button>
		
		<br><br>
		<button type="button" onclick="window.open('js_math.html')">跳转JS算法题</button>
	</body>
	<script type="text/javascript">
	
		function question1() {
			for (var i = 1; i <= 9; i++) {
				for (var a = 1, b = ''; a <= i; a++) {
					b += a + '*' + i + '=' + i * a + ' ';
				}
				console.log(b)
			}
		}	
		//question2答案参考CSDN原创作者Jeff1804。
		//斐波那契数列解法1-递归-当参数n变大时，出现浏览器假死现象。
		//递归非常耗费内存，因为需要同时保存成千上百个调用记录，很容易发生"栈溢出"错误（stack overflow）。
		function fb1(n) {
			if (n <= 2) {
				return 1;
			} else {
				return fb1(n - 1) + fb1(n - 2);
			}
		}

		//斐波那契数列解法2-递归方法基础上进行尾调用优化-通过默认参数来将加法操作移出return语句
		//尾调用优化参考https://www.cnblogs.com/aizzz/p/9792733.html
		function fb2(n, res1 = 1, res2 = 1) {
			if (n <= 2) {
				return res2;
			} else {
				return fb2(n - 1, res2, res1 + res2);
			}
		}
		//斐波那契数列解法3-迭代
		//递归和迭代：递归重复调用本身；迭代重复调用反馈值
		function fb3(n) {
			var res1 = 1,
				res2 = 1,
				sum = res2;
			for (var i = 2; i < n; i++) {
				sum = res1 + res2;
				res1 = res2;
				res2 = sum;
			}
			return sum;
		}

		//斐波那契数列解法4-闭包
		function fb4(n) {
			var mem = [0, 1];

			function yy(n) {
				var res = mem[n];
				if (typeof res !== "number") {
					mem[n] = yy(n - 1) + yy(n - 2);
					res = mem[n];
				}
				return res;
			}
			return yy(n);
		};

		//打印斐波那契数列
		function fib(num) {
			var arr = []
			if (num == 1) {
				return arr = [1]
			} else if (num == 2) {
				return arr = [1, 1]
			} else {
				arr = [1,1]
				var a=1,b=1,c=2
				for ( var i=2;i<num;i++ ){
					arr.push(c)
					a=b
					b=c
					c=a+b					
				}
				return arr
			}
		}


		function question2(n) {
			//var fb_num = fb1(n)
			//var fb_num = fb2(n,1,1)
			//var fb_num = fb3(n)
			//var fb_num = fb4(30)		
			//console.log(fb_num) //832040
			var fb_arr =fib(30);
			console.log(fb_arr) 
			//[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040]
		}
	</script>
</html>
